package com.cavy.platform.client;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
 * bean支持类
 */
@Component
public class BeansProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeansProvider.applicationContext = applicationContext;
    }

    /**
     * 根据类名称获取bean
     *
     * @param clazz 目标类class
     * @param <T>   目标类泛型
     * @return spring管理的bean, 如果不存在则返回null
     */
    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    public static <T> Collection<T> getBeans(Class<T> clazz) {
        if (applicationContext == null) {
            return Collections.emptyList();
        }
        Map<String, T> beansOfType = applicationContext.getBeansOfType(clazz);
        return beansOfType.values();
    }
}
